#!/usr/bin/env python
import getopt
import sys
import commands
from string import strip


_cli_probeport = "netstat -an|grep %d|grep LISTEN|wc -l"
_cli_killpfile = "kill -9 `cat %s`"
_cli_killpname = "killall %s"



def proboport(port):
    cli = _cli_probeport % port
    status,output = commands.getstatusoutput(cli)
    c = int(strip(output))
    return  c > 0

def killprocess(pidfile="",pname=""):
    if pidfile == "" && pname == "":
        print "pidfile and pname is empty"
        sys.exit(-1)

    cli = ""
    if pidfile != "":
        cli = _cli_killpfile % pidfile

    if pname != "":
        cli = _cli_killpname % pname

    if cli != "":
        status,output = commands.getstatusoutput(cli)
        return status == 0
    else:
        return False

def cpuusage():
    cmd = """iostat|head -n4|tail -n1|awk '{print $1}'"""
    status,output = commands.getstatusoutput(cmd)
    return output


def runcli(cli):
    if cli == "":
        print "please set param -p."
        sys.exit(-1)

    status,output = commands.getstatusoutput(cli)
    return output

def free():
    cmd = """vmstat|head -n3|tail -n1|awk '{print $4}'"""
    status,output = commands.getstatusoutput(cmd)
    return output








if __name__ == '__main__':
    opts,args = getopt.getopt(sys.argv[1:],"hvc:p:",["help","version","cmd","port"])

    
    param = ""
    cmd = ""
    for k,v in opts:
        if k == "-c":
            cmd = v
        elif k == "-p":
            print v
            param = strip(v)

    
    if cmd == "pp":
        print proboport(int(param))
    elif cmd == "run":
        print runcli(param)
    elif cmd == "kpf":        
        print killprocess(pidfile=param)
    elif cmd == "kpn":
        print killprocess(pname=param)
    elif cmd == "cpu":
        print cpuusage()
    elif cmd == "free":
        print free()
    else:        
        print "No!"
        sys.exit(0)







    
        
